package com.xopencode.io.demo;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author Mcb
 * @date 2022/5/5
 * @apiNote
 */
public class Service {
    public static void main(String[] args) throws IOException {
        //服务端通道
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(10086));
        serverSocketChannel.configureBlocking(false);

        Selector selector = Selector.open();
        //注册到复用器中，每当有请求操作就会触发该通道
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            if (selector.select(3000) == 0) {
                System.out.println("暂未有请求");
                continue;
            }
            //获取全部注册在分发器的通道及对于事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                if (selectionKey.isAcceptable()) {
                    //接受客户端请求
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    //将请求注册为读事件到复用器中
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    System.out.println("来自客户端的注册信息："+socketChannel.getLocalAddress().toString());
                }
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    //从通道将数据读入缓冲区
                    channel.read(byteBuffer);
                    System.out.println("来自客户端的信息：" + new String(byteBuffer.array()));
                }
                iterator.remove();
            }
        }

    }
}
